package com.chance.cc.crawler.development.scripts.cnbeverage;

import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.article;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2020/11/24 9:54
 * @Description
 *      饮料行业网 热点
 **/
public class CnbeverageArticleListCrawlerScript extends CrawlerCommonScript {

    private Logger log = LoggerFactory.getLogger(CnbeverageArticleListCrawlerScript.class);
    public static final String prefixUrl = "http://www.cnbeverage.com";

    public static final String turnPageUrl = "http://www.cnbeverage.com/news/articlelist/page\\S*";//翻页地址
    public static final String articleUrl = "http://www.cnbeverage.com/news/detail/id/\\S*\\.html";//文章地址

    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return "cnbeverage";
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(turnPageUrl);
        addUrlRegular(articleUrl);

    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }


    /**
     * 解析链接方法
     *
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();

        String requestUrl = httpPage.getRequest().getUrl();

        if(requestUrl.matches(turnPageUrl)){
            String nextPageUrl = httpPage.getHtml().xpath("//span[@class=\"current_x\"]/../@href").get();
            if(StringUtils.isNotEmpty(nextPageUrl)){
                nextPageUrl = prefixUrl + nextPageUrl;
                CrawlerRequestRecord turnPageRequest = CrawlerRequestRecord.builder()
                        .turnPageRequest(crawlerRequestRecord)
                        .recordKey(nextPageUrl)
                        .httpUrl(nextPageUrl)
                        .releaseTime(System.currentTimeMillis())
                        .build();
                parsedLinks.add(turnPageRequest);
            }

            List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"bp-head\"]").nodes();
            for (Selectable node : nodes) {
                String itemUrl =  node.xpath("./h2/a/@href").get();
                if (StringUtils.isBlank(itemUrl)) {
                    continue;
                }else{
                    itemUrl = prefixUrl + itemUrl;
                }

                String releaseTime = node.xpath(".//span[@class=\"entry-date\"]/text()").get();
                if (StringUtils.isBlank(releaseTime)) {
                    continue;
                }else{
                    releaseTime = releaseTime.substring(releaseTime.indexOf("：") + 1).trim();
                }

                try {
                    Long releaseTimeToLong = DateUtils.parseDate(releaseTime, "yyyy年MM月dd日 HH:mm").getTime();

                    CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(itemUrl)
                            .httpUrl(itemUrl)
                            .releaseTime(releaseTimeToLong)
                            .needParsed(false)
                            .resultLabelTag(article)
                            .build();

                    parsedLinks.add(itemRecord);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return parsedLinks;
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();
        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));

        }

        return crawlerDataList;
    }

    public CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {

        List<String> articleTextList = httpPage.getHtml().xpath("//div[@class=\"entry-content\"]/p//text()").all();
        StringBuffer conents = new StringBuffer();
        for (String articleText : articleTextList) {
            conents.append(articleText).append(" ");
        }

        String title = httpPage.getHtml().xpath("//h1[@class=\"post-tile entry-title\"]//text()").get();

        String author =  httpPage.getHtml().xpath("//span[@class=\"fn\"]//text()").get();
        String releaseTime = httpPage.getHtml().xpath("//a[@class=\"updated\"]").get();

        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1, itemUrl.lastIndexOf("."));

        CrawlerData crawlerData = null;
        try {
            crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                    .url(itemUrl)
                    .releaseTime(DateUtils.parseDate(releaseTime, "yyyy年MM月dd日 HH:mm").getTime())
                    .addContentKV(Field_Content, StringEscapeUtils.unescapeHtml4(conents.toString().trim()))
                    .addContentKV(Field_Title, StringEscapeUtils.unescapeHtml4(title))
                    .addContentKV(Field_Author, author)
                    .build();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return crawlerData;

    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

}
